package com.shangyitong.yygh_hosp.service.impl;

import com.shangyitong.yygh.model.hosp.Department;
import com.shangyitong.yygh.vo.hosp.DepartmentVo;
import com.shangyitong.yygh_hosp.repository.DepartmentRepository;
import com.shangyitong.yygh_hosp.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentRepository departmentRepository;
    @Override
    public List<DepartmentVo> getDeptList(String hoscode) {
        //创建集合
        List<DepartmentVo> result = new ArrayList<>();
        //查找所有部门
        Department departmentQuery = new Department();
        departmentQuery.setHoscode(hoscode);
        Example<Department> example = Example.of(departmentQuery);
        List<Department> departmentList = departmentRepository.findAll(example);
        //对所有部门根据BigCode进行分组
        Map<String, List<Department>> departmentMap =
                departmentList.stream().collect(Collectors.groupingBy(Department::getBigcode));
        for (Map.Entry<String, List<Department>> entry : departmentMap.entrySet()) {
            //第一轮分组，对BigCode和Bigname进行分组且分装
            String bigCode = entry.getKey();
            List<Department> departments = entry.getValue();
            DepartmentVo departmentVoFirst = new DepartmentVo();
            departmentVoFirst.setDepcode(bigCode);
            departmentVoFirst.setDepname(departments.get(0).getBigname());
            //第二轮分组
            List<DepartmentVo> children = new ArrayList<>();
            for (Department department : departments) {
                DepartmentVo departmentVoSecond = new DepartmentVo();
                departmentVoSecond.setDepcode(department.getDepcode());
                departmentVoSecond.setDepname(department.getDepname());
                children.add(departmentVoSecond);
            }
            //整体分装
            departmentVoFirst.setChildren(children);
            result.add(departmentVoFirst);
        }
        return result;
    }
}
